package com.sfac.hqyj.springBoot.interceptor;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class RequestViewMappingInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(RequestViewMappingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        LOGGER.debug("==== Pre Interceptor ====");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        LOGGER.debug("==== Post Interceptor ====");

        // 接口、重定向、转发 无需处理
        if (modelAndView == null ||
                modelAndView.getViewName().toLowerCase().startsWith("redirect") ||
                modelAndView.getViewName().toLowerCase().startsWith("forward")) {
            return;
        }

        String path = request.getServletPath();
        LOGGER.debug(request.getServletPath() + "--" + request.getRequestURI());
        String template = (String) modelAndView.getModelMap().getAttribute("template");
        if (StringUtils.isBlank(template) && StringUtils.isNotBlank(path)) {
            if (path.startsWith("/")){
                path = path.substring(1, path.length());
            }
            modelAndView.getModelMap().addAttribute("template", path);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        LOGGER.debug("==== After Interceptor ====");
    }
}
